//
//  AGDCVideFrame.cpp
//  AgoraDemo
//
//  Created by tzx on 16/10/17.
//  Copyright © 2016年 apple. All rights reserved.
//

#define MAX_YUV_LEN     (1280*720*3/2)


#include "AGDCVideoFrameObserver.hpp"

CVideoFrameObserver::CVideoFrameObserver()
{
    mWidth = 480;
    mHeight = 640;
    ::createVideoPool((void**)&mVideoFrameBufferPool, mWidth, mHeight, 0);
    
    mYuvBuf = (uint8_t*)malloc(MAX_YUV_LEN);
}

CVideoFrameObserver::~CVideoFrameObserver()
{
    
}

bool CVideoFrameObserver::inputVideoFrame(uint8_t *data, int len, int width, int height, int rawType)
{
    return ::pushVideoFrame(mVideoFrameBufferPool, data, len, width, height, rawType);
}


bool CVideoFrameObserver::onCaptureVideoFrame(VideoFrame& videoFrame)
{
    bool bRet = true;
    
    unsigned char *pData = NULL;
    int frameSize = 0;
    int width;
    int height;
    
    bRet = ::getVideoFrameBegin(mVideoFrameBufferPool, &pData, &width, &height, &frameSize);
    if(false == bRet){
        return bRet;
    }
    
    int ysize = width*height;
    int halfhalfYsize = ysize >> 2;
    memcpy(videoFrame.yBuffer, pData, ysize);
    memcpy(videoFrame.uBuffer, pData + ysize, halfhalfYsize);
    memcpy(videoFrame.vBuffer, pData + halfhalfYsize*5, halfhalfYsize);
    
    videoFrame.yStride = width;
    videoFrame.uStride = (width+1)/2;
    videoFrame.vStride =  (width+1)/2;
    videoFrame.width = width;
    videoFrame.height = height;
    
    ::getVideoFrameEnd(mVideoFrameBufferPool);
    
    return bRet;
}


bool CVideoFrameObserver::onRenderVideoFrame(unsigned int uid, VideoFrame& videoFrame)
{
    bool bRet = true;
    
    //printf("uid :%u, w*h[%d*%d], ybuf:%p, ubuf:%p, vbuf:%p\n", uid, videoFrame.width, videoFrame.height, videoFrame.yBuffer
    //       ,videoFrame.uBuffer, videoFrame.vBuffer);
    
    if(m_callback){
        int yFrameLen = videoFrame.width*videoFrame.height;
        memset(mYuvBuf, 0, MAX_YUV_LEN);
        memcpy(mYuvBuf, videoFrame.yBuffer, yFrameLen);
        memcpy(mYuvBuf + yFrameLen, videoFrame.uBuffer, yFrameLen/4);
        memcpy(mYuvBuf + yFrameLen*5/4, videoFrame.vBuffer, yFrameLen/4);
        int nLen = yFrameLen*3/2;
        
        m_callback(mYuvBuf, nLen, videoFrame.width, videoFrame.height, 0, false, m_context);
    }
    return bRet;
}
    
